package com.chen.order.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.chen.feign.cart.CartFeignClient;
import com.chen.feign.product.ProductFeignClient;
import com.chen.feign.user.UserFeignClient;
import com.chen.model.dto.h5.OrderInfoDto;
import com.chen.model.entity.h5.CartInfo;
import com.chen.model.entity.order.OrderInfo;
import com.chen.model.entity.order.OrderItem;
import com.chen.model.entity.order.OrderLog;
import com.chen.model.entity.product.ProductSku;
import com.chen.model.entity.user.UserAddress;
import com.chen.model.entity.user.UserInfo;
import com.chen.model.vo.common.ResultCodeEnum;
import com.chen.model.vo.h5.TradeVo;
import com.chen.order.enums.OperatorType;
import com.chen.order.mapper.OrderInfoMapper;
import com.chen.order.mapper.OrderItemMapper;
import com.chen.order.mapper.OrderLogMapper;
import com.chen.order.service.OrderService;
import com.chen.service.exception.MyException;
import com.chen.service.util.AuthContextUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author cgj
 * @date 4/26/25 10:23 AM
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private CartFeignClient cartFeignClient;
    @Autowired
    private ProductFeignClient productFeignClient;
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private OrderLogMapper orderLogMapper;

    /**
     * 返回购物车订单生成前准备的数据
     *
     * @return
     */
    @Override
    public TradeVo trade() {
        //当前用户地址信息
        List<CartInfo> allChecked = cartFeignClient.getAllChecked();
        if (CollectionUtil.isEmpty(allChecked)) {
            throw new MyException(ResultCodeEnum.DATA_ERROR);
        }
        List<OrderItem> orderItemList = allChecked.stream().map(cartinfo -> {
            //orderItem是具体的商品项, 一个cartInfo对应多个orderItem
            OrderItem orderItem = new OrderItem();
            orderItem.setSkuId(cartinfo.getSkuId());
            orderItem.setSkuName(cartinfo.getSkuName());
            orderItem.setThumbImg(cartinfo.getImgUrl());
            orderItem.setSkuNum(cartinfo.getSkuNum());
            orderItem.setSkuPrice(cartinfo.getCartPrice());
            return orderItem;
        }).collect(Collectors.toList());


        // 计算金额
        BigDecimal totalAmount = new BigDecimal(0);
        for (CartInfo cartInfo : allChecked) {
            BigDecimal num = BigDecimal.valueOf(cartInfo.getSkuNum());
            BigDecimal price = cartInfo.getCartPrice();
            totalAmount = totalAmount.add(num.multiply(price));
        }

        //封装数据
        TradeVo tradeVo = new TradeVo();
        tradeVo.setTotalAmount(totalAmount);
//        tradeVo.setTotalAmount(BigDecimal.valueOf(100));
        tradeVo.setOrderItemList(orderItemList);
        return tradeVo;
    }

    /**
     * 返回订单号(订单id)
     *
     * @param orderInfoDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class, readOnly = false)
    public Long submitOrder(OrderInfoDto orderInfoDto) {
        //获取订单项集合
        List<OrderItem> orderItemList = orderInfoDto.getOrderItemList();
        if (CollectionUtil.isEmpty(orderItemList)) {
            throw new MyException(ResultCodeEnum.DATA_ERROR);
        }
        //总金额
        BigDecimal total = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) { //计算总金额

            total = total.add(BigDecimal.valueOf(orderItem.getSkuNum()).multiply(orderItem.getSkuPrice()));
            //获取商品sku信息
            Long skuId = orderItem.getSkuId();


            ProductSku productsku = productFeignClient.getProductSkuBySkuId(skuId);
            if (productsku == null) {
                throw new MyException(ResultCodeEnum.DATA_ERROR);
            }
            //比较购买数和库存数
            if (productsku.getStockNum().intValue() <orderItem.getSkuNum().intValue()) {
                throw new MyException(ResultCodeEnum.STOCK_LESS);
            }
        }
        UserAddress userAddr = userFeignClient.getAddrById(orderInfoDto.getUserAddressId());

        //封装orderInfo数据
        //需要用到user的数据
        UserInfo userInfo = AuthContextUtil.get();
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(userInfo.getId());
        orderInfo.setNickName(userInfo.getNickName());
        //这个订单号是和支付宝对接的,需要保证唯一
        orderInfo.setOrderNo(String.valueOf(System.currentTimeMillis()));
        orderInfo.setCouponAmount(BigDecimal.valueOf(0));
        orderInfo.setTotalAmount(total);
        orderInfo.setOriginalTotalAmount(total);
        orderInfo.setPayType(2);
        //运费
        orderInfo.setFeightFee(new BigDecimal(0));
        orderInfo.setFeightFee(orderInfoDto.getFeightFee());
        //地址相关的数据
        orderInfo.setReceiverName(userAddr.getName());
        orderInfo.setReceiverPhone(userAddr.getPhone());
        orderInfo.setReceiverTagName(userAddr.getTagName());
        orderInfo.setReceiverProvince(userAddr.getProvinceCode());
        orderInfo.setReceiverCity(userAddr.getCityCode());
        orderInfo.setReceiverDistrict(userAddr.getDistrictCode());
        orderInfo.setReceiverAddress(userAddr.getAddress());
        orderInfo.setRemark(orderInfoDto.getRemark());
        orderInfo.setOrderStatus(0);
        //保存orderInfo, 而且需要回传订单id
        orderInfoMapper.insertOrderInfo(orderInfo);
        //补充orderItem数据
        for (OrderItem item : orderItemList) {
            //设置订单id
            item.setOrderId(orderInfo.getId());
            //保存
            orderItemMapper.insertOrderItem(item);
        }
        //封装orderLog
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderInfo.getId());
        orderLog.setOperateUser(OperatorType.MOBILE.name());
        orderLog.setProcessStatus(0);
        orderLog.setNote("提交订单");
        orderLogMapper.insertOrderLog(orderLog);

        //TODO 清除用户已经加入订单的购物项(用户选中的)
        cartFeignClient.deleteChecked();


        return orderInfo.getId();
    }

    /**
     * 直接购买 不进入购物车
     *
     * @param skuId
     * @return
     */
    @Override
    public TradeVo buy(Long skuId) {
        //根据skuId查询sku
        ProductSku productsku = productFeignClient.getProductSkuBySkuId(skuId);
        if (productsku == null || productsku.getStockNum().intValue() < 1) {
            throw new MyException(ResultCodeEnum.STOCK_LESS);
        }

        // 封装对象
        TradeVo tradeVo = new TradeVo();
        tradeVo.setTotalAmount(productsku.getSalePrice());
        ArrayList<OrderItem> orderItemList = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        orderItem.setSkuId(productsku.getId());
        orderItem.setSkuPrice(productsku.getSalePrice());
        orderItem.setThumbImg(productsku.getThumbImg());
        orderItem.setSkuNum(1);
        orderItem.setSkuName(productsku.getSkuName());
        orderItemList.add(orderItem);
        tradeVo.setOrderItemList(orderItemList);
        return tradeVo;
    }

    /**
     * 根据订单id,获取订单信息
     *
     * @param orderId
     * @return
     */
    @Override
    public OrderInfo getOrderInfo(Long orderId) {
        OrderInfo orderInfo = orderInfoMapper.getById(orderId);
        return orderInfo;
    }

    /**
     * 根据订单状态,查询订单信息
     *
     * @param pageNum
     * @param pageSize
     * @param orderStatus
     * @return
     */
    @Override
    public PageInfo selectByOrderStatus(Integer pageNum, Integer pageSize, Integer orderStatus) {
        //开启分页
        PageHelper.startPage(pageNum, pageSize);
        Long userid = AuthContextUtil.get().getId();
        List<OrderInfo> orderInfoList = orderInfoMapper.selectByOrderStatus(orderStatus,userid);
        //封装订单项
        if(CollectionUtil.isEmpty(orderInfoList)){
            return new PageInfo();
        }
        for (OrderInfo orderInfo : orderInfoList) {
            List<OrderItem> orderItemList = orderItemMapper.getOrderItemByOrderId(orderInfo.getId());
            orderInfo.setOrderItemList(orderItemList);
        }
        return new PageInfo(orderInfoList);
    }

    /**
     * 根据orderNo查询订单信息
     * @param orderNo
     * @return
     */
    @Override
    public OrderInfo getOrderInfoByOrderNo(String orderNo) {
        //查询订单信息
        OrderInfo orderInfo = orderInfoMapper.selectByOrderNo(orderNo);
        //查询订单项列表
        List<OrderItem> orderItemList = orderItemMapper.getOrderItemByOrderId(orderInfo.getId());
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }

    /**
     * 根据OrderNo修改订单的状态
     * @param orderStatus
     * @param orderNo
     */

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateOrderByOrderNo(Integer orderStatus, String orderNo) {
        OrderInfo orderInfo = orderInfoMapper.selectByOrderNo(orderNo);
        //封装数据
        orderInfo.setOrderStatus(orderStatus);
        orderInfo.setPaymentTime(new Date());
        orderInfo.setOrderNo(orderNo); // 修改的条件
        //更新 orderInfo表
        //根据orderId修改
        orderInfoMapper.updateOrderInfoByOrderId(orderInfo);
        //更新日志
        OrderLog orderLog = new OrderLog();
        orderLog.setNote("支付成功");
        orderLog.setProcessStatus(orderStatus);
        orderLog.setOrderId(orderInfo.getId());//修改的条件
        //根据orderId修改
        orderLogMapper.updateOrderLogByOrderId(orderLog);
    }

}
